<?php
/**
 * @email wei@alipay168.cn
 * @author 小韦
 * @link http://blog.alipay168.cn
 * @Date: 2020/3/24 19:58
 */

namespace app\server;


use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use think\Db;

class EmailServer
{
    /**
     * setSubject()：邮件主题
     *
     * setFrom()：发件人地址，数组形式，可以是多个发件人
     *
     * setTo()：收件人地址，数组形式，可以是多个收件人
     *
     * setBody()：邮件内容
     *
     * addPart()：邮件内容指定输出类型，支持html内容输出
     *
     * attach()：添加附件
     *
     * setCc()：抄送，支持多个邮箱地址
     *
     * setBcc()：密送，支持多个邮箱地址
     *
     * @param $sendTo array sendTo:['aaa@abc.com','aadfw@dwo.com'=>'昵称']
     * @param $html string 支持html发送
     * @param  $title string 发送的标题
     */
    public static function send_mail($sendTo = [], $html = '', $title = '', $user_id=1)
    {
        $config = Db::name('config_email')->where(['user_id'=>$user_id])->find();
        if (!$config) {
            return ['code'=>-1,'msg'=>'邮箱未配置'];
        }
        // Create the Transport,$encryption(tls or ssl)
        $transport = (new Swift_SmtpTransport($config['host'], $config['port'],$config['encryption']))
            ->setUsername($config['username'])
            ->setPassword($config['user_pwd']);
        // Create the Mailer using your created Transport
        $mailer = new Swift_Mailer($transport);
        // Create a message

        $message = (new Swift_Message($title))
            ->setSubject($title)
            ->setFrom([$config['username'] => '小程序996'])
            ->setTo($sendTo)
            //->setBody($txt)
            ->addPart($html, 'text/html');
        // Send the message
        $result = $mailer->send($message);
        if ($result) {
            return ['code'=>0,'msg'=>'发送成功'];
        }
        return ['code'=>-1,'msg'=>'发送失败'];
    }
}